import { Service } from 'egg';
import { MsgStatus } from '../../model/msg';

export default class DbMsgService extends Service {
    public async getByPage(adminId: number, page: number, pageSize: number) {
        const mysql = this.app.mysql;
        return await mysql.select('admin_message', {
            where: {
                admin_id: adminId,
            },
            orders: [['status', 'ASC'], ['created_at', 'DESC']],
            limit: pageSize,
            offset: (page - 1) * pageSize,
        });
    }

    public async getCountByAdmin(adminId: number) {
        const mysql = this.app.mysql;
        return await mysql.count('admin_message', { admin_id: adminId });
    }

    public async update(id: number, data: object) {
        const mysql = this.app.mysql;
        await mysql.update('admin_message', {
            ...data,
            updated_at: mysql.literals.now,
        }, { where: { id } });
    }

    public async create(adminId: number, msg: string) {
        const mysql = this.app.mysql;
        await mysql.insert('admin_message', {
            admin_id: adminId,
            msg,
            created_at: mysql.literals.now,
            updated_at: mysql.literals.now,
            status: MsgStatus.Unread,
        });
    }

    public async delete(msgId: number) {
        const mysql = this.app.mysql;
        await mysql.delete('admin_message', { id: msgId });
    }
}
